package com.hunttown.common.sharding.client.rule;

import com.hunttown.common.sharding.client.util.MurmurHash;

public class SimpleRouteRule implements RouteRule<Object> {
    private int dbsCount;
    private int tablesCount;
    private int tablesCountPerDb;

    public SimpleRouteRule(int dbsCount, int tablesCount) {
        if (dbsCount > 0 && tablesCount > 0) {
            this.dbsCount = dbsCount;
            this.tablesCount = tablesCount;
            this.tablesCountPerDb = tablesCount / dbsCount;
            if (this.tablesCountPerDb == 0) {
                throw new IllegalArgumentException("the expression 'tablesCount/dbsCount'==0!");
            }
        } else {
            throw new IllegalArgumentException("dbsCount and tablesCount must be both positive!");
        }
    }

    public int getDbIndex(Object routeFactor) {
        if (!(routeFactor instanceof Integer) && !(routeFactor instanceof Long) && !(routeFactor instanceof String)) {
            throw new IllegalArgumentException("Unsupported RouteFactor parameter type! the support RouteFactor parameter is Integer, Long and String.");
        } else {
            return (int) (Math.abs(MurmurHash.hash(String.valueOf(routeFactor))) % (long) this.tablesCount / (long) this.tablesCountPerDb);
        }
    }

    public int getTableIndex(Object routeFactor) {
        if (!(routeFactor instanceof Integer) && !(routeFactor instanceof Long) && !(routeFactor instanceof String)) {
            throw new IllegalArgumentException("Unsupported RouteFactor parameter type! the support RouteFactor parameter is Integer, Long and String.");
        } else {
            return (int) (Math.abs(MurmurHash.hash(String.valueOf(routeFactor))) % (long) this.tablesCount);
        }
    }
}